<?php
class ModelCatalogProduct extends Model {
	public function addProduct($data) {
        if(!isset($data['model'])){
            $data['model'] = '';
        }
        
        if(!isset($data['product_cross_related'])){
            $data['product_cross_related'] = 0;    
        }
        
		if(!isset($data['delay_delivery'])){
            $data['delay_delivery'] = '0';
        }
		
        $sql_product = "INSERT INTO " . DB_PREFIX . "product " .
            " SET " .
            "   model = '" . $this->db->escape($data['model']) . "', sku = '" . $this->db->escape($data['sku']) . "', location = '" . $this->db->escape($data['location']) . "', " .
            "   quantity = '" . (int)$data['quantity'] . "', minimum = '" . (int)$data['minimum'] . "', subtract = '" . (int)$data['subtract'] . "', " .
            "   stock_status_id = '" . (int)$data['stock_status_id'] . "', date_available = '" . $this->db->escape($data['date_available']) . "', " .
            "   manufacturer_id = '" . (int)$data['manufacturer_id'] . "', shipping = '" . (int)$data['shipping'] . "', price = '" . (float)$data['price'] . "', cost = '" . (float)$data['cost'] . "', " .
            "   weight = '" . (float)$data['weight'] . "', weight_class_id = '" . (int)$data['weight_class_id'] . "', length = '" . (float)$data['length'] . "', width = '" . (float)$data['width'] . "', " .
            "   height = '" . (float)$data['height'] . "', length_class_id = '" . (int)$data['length_class_id'] . "', status = '" . (int)$data['status'] . "', tax_class_id = '" . (int)$data['tax_class_id'] . "', " .
            "   sort_order = '" . (int)$data['sort_order'] . "', date_added = NOW(), size_guide = '" . $data['size_guide'] . "', cross_reference = '" . (int)$data['product_cross_related'] . "', product_number = '" . $data['product_number'] . "', " .
            "   low_stock_warning = '" . (int)$data['low_stock_warning'] . "', delivery_time_instock = '" . $this->db->escape($data['delivery_time_instock']) . "', delivery_time_outstock = '" . $this->db->escape($data['delivery_time_outstock']) . "', " . 
			"   youtube_video = '" . $this->db->escape($data['youtube_video']) . "', youtube_video_width = '" . (int)$data['youtube_video_width'] . "', youtube_video_height = '" . (int)$data['youtube_video_height'] . "', delay_delivery = '" . (int)$data['delay_delivery'] . "'";
		$this->db->query($sql_product);
		
		$product_id = $this->db->getLastId();
		
		if (isset($data['image'])) {
			$this->db->query("UPDATE " . DB_PREFIX . "product SET image = '" . $this->db->escape($data['image']) . "' WHERE product_id = '" . (int)$product_id . "'");
		}
		
        if (isset($data['video'])) {
            $this->db->query("UPDATE " . DB_PREFIX . "product SET video = '" . $this->db->escape($data['video']) . "' WHERE product_id = '" . (int)$product_id . "'");
        }
        
		foreach ($data['product_description'] as $language_id => $value) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "product_description SET product_id = '" . (int)$product_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "', meta_keywords = '" . $this->db->escape($value['meta_keywords']) . "', meta_description = '" . $this->db->escape($value['meta_description']) . "', description = '" . $this->db->escape($value['description']) . "'");
		}
		
		if (isset($data['product_store'])) {
			foreach ($data['product_store'] as $store_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_to_store SET product_id = '" . (int)$product_id . "', store_id = '" . (int)$store_id . "'");
			}
		}
		 
		if (isset($data['product_option'])) {
			foreach ($data['product_option'] as $product_option) {    
                if($this->isSaveOption($product_option['product_option_value'])){ 
				    $this->db->query("INSERT INTO " . DB_PREFIX . "product_option SET product_id = '" . (int)$product_id . "', sort_order = '" . (int)$product_option['sort_order'] . "', attribute_id = '" . (int)$product_option['attribute_id'] . "', is_complex = '0'");
				    
				    $product_option_id = $this->db->getLastId();
				    
				    foreach ($product_option['language'] as $language_id => $language) {
					    $this->db->query("INSERT INTO " . DB_PREFIX . "product_option_description SET product_option_id = '" . (int)$product_option_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = '" . $this->db->escape($language['name']) . "'");
				    }	
				    
				    foreach ($product_option['product_option_value'] as $product_option_value) {
                        if(isset($product_option_value['select_attribute'])){
						    $this->db->query("INSERT INTO " . DB_PREFIX . "product_option_value SET product_option_id = '" . (int)$product_option_id . "', product_id = '" . (int)$product_id . "', quantity = '" . (int)$product_option_value['quantity'] . "', subtract = '" . (int)$product_option_value['subtract'] . "', price = '" . (float)$product_option_value['price'] . "', prefix = '" . $this->db->escape($product_option_value['prefix']) . "', sort_order = '" . (int)$product_option_value['sort_order'] . "', attribute_id = '" . (int)$product_option_value['attribute_id'] . "', attribute_value_id = '" . (int)$product_option_value['attribute_value_id'] . "', product_option_number = '" . $this->db->escape($product_option_value['product_option_number']) . "'");
				    
						    $product_option_value_id = $this->db->getLastId();
				    
						    foreach ($product_option_value['language'] as $language_id => $language) {
							    $this->db->query("INSERT INTO " . DB_PREFIX . "product_option_value_description SET product_option_value_id = '" . (int)$product_option_value_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = '" . $this->db->escape($language['name']) . "'");
						    }		
                        }			
				    }
				}
			}
		}
		
		if (isset($data['product_discount'])) {
			foreach ($data['product_discount'] as $value) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_discount SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$value['customer_group_id'] . "', quantity = '" . (int)$value['quantity'] . "', priority = '" . (int)$value['priority'] . "', price = '" . (float)$value['price'] . "', date_start = '" . $this->db->escape($value['date_start']) . "', date_end = '" . $this->db->escape($value['date_end']) . "'");
			}
		}

		if (isset($data['product_special'])) {
			foreach ($data['product_special'] as $value) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_special SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$value['customer_group_id'] . "', priority = '" . (int)$value['priority'] . "', price = '" . (float)$value['price'] . "', date_start = '" . $this->db->escape($value['date_start']) . "', date_end = '" . $this->db->escape($value['date_end']) . "', quantity = '" . (int)$value['quantity'] . "'");
			}
		}
		
		if (isset($data['product_image'])) {
			foreach ($data['product_image'] as $image) {
                if($image){
        		    $this->db->query("INSERT INTO " . DB_PREFIX . "product_image SET product_id = '" . (int)$product_id . "', image = '" . $this->db->escape($image) . "'");
                }
			}
		}
		
		if (isset($data['product_download'])) {
			foreach ($data['product_download'] as $download_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_to_download SET product_id = '" . (int)$product_id . "', download_id = '" . (int)$download_id . "'");
			}
		}
		
		if (isset($data['product_category'])) {
			foreach ($data['product_category'] as $category_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_to_category SET product_id = '" . (int)$product_id . "', category_id = '" . (int)$category_id . "'");
			}
		}
		           
		if (isset($data['product_related'])) {  
            if(isset($data['product_cross_related'])){ 
			    foreach ($data['product_related'] as $related_id) {
				    $this->db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$product_id . "', related_id = '" . (int)$related_id . "'");                    
				    $this->db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$related_id . "', related_id = '" . (int)$product_id . "'");
                }
			} else{
                foreach ($data['product_related'] as $related_id) {
                    $this->db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$product_id . "', related_id = '" . (int)$related_id . "'");                                        
                }    
            }
		}
				
		if (isset($data['product_color'])) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "product_option SET product_id = '" . (int)$product_id . "', attribute_id = '" . (int)$data['color_attribute_id'] + "', sort_order = '10', is_complex = '1'");				
			$option_id = $this->db->getLastId();			
			foreach ($data['product_color_language'] as $language_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_option_description SET product_option_id = '" . (int)$option_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = 'Farve'");
			}
						
			foreach ($data['product_color'] as $color) {        		
        		$this->db->query("INSERT INTO " . DB_PREFIX . "product_option_value SET product_option_id = '" . (int)$option_id . "', product_id = '" . (int)$product_id . "', quantity = '1000', subtract = '1', price = '0', prefix = '+', sort_order = '0'");        									
        		$option_value_id = $this->db->getLastId();
				foreach ($data['product_color_language'] as $language_id) {
					$this->db->query("INSERT INTO " . DB_PREFIX . "product_option_value_description SET product_option_value_id = '" . (int)$option_value_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = '" . $this->db->escape($color['name']) . "'");
				}				
				
				if(isset($color['image_list'])){
					reset($color['image_list']);
					$color_image = current($color['image_list']);
				}
				
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_color SET product_id = '" . (int)$product_id . "', image = '" . $this->db->escape($color_image) . "', color_name='" . $this->db->escape($color['name']) . "', color_image='" . $this->db->escape($color['color_image']) . "', option_id = '" . (int)$option_id . "', option_value_id = '" . (int)$option_value_id . "', attribute_id = '" . (int)$data['color_attribute_id'] . "', attribute_value_id = '" . (int)$color['color_av_id'] . "'");
				if(isset($color['image_list'])){
					$color_id = $this->db->getLastId();
					foreach ($color['image_list'] as $image) {
						$this->db->query("INSERT INTO " . DB_PREFIX . "product_color_image SET product_id = '" . (int)$product_id . "', color_id = '" . (int)$color_id . "', image = '" . $this->db->escape($image) . "'");
					} 
				}           		
			}
		}
		
		if ($data['keyword']) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'product_id=" . (int)$product_id . "', keyword = '" . $this->db->escape($data['keyword']) . "'");
		}
		
		foreach ($data['product_tags'] as $language_id => $value) {
			$tags = explode(',', $value);
			foreach ($tags as $tag) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_tags SET product_id = '" . (int)$product_id . "', language_id = '" . (int)$language_id . "', tag = '" . $this->db->escape(trim($tag)) . "'");
			}
		}
				
		if (isset($data['product_category'])) {			
			foreach ($data['product_category'] as $category_id) {
				$new_sorts = array(
					'sort_id'           => 0,
					'product_id'        => $product_id,
					'sort_order'        => 1,
					'sort_order_old'    => 0,
					'category_id'       => $category_id,
					'manufacturer_id' 	=> $data['manufacturer_id'],
				);
				
				$this->load->model('catalog/product_sort');
				$this->model_catalog_product_sort->addSortByCategory($new_sorts);
				$this->model_catalog_product_sort->addSortByManufacturer($new_sorts);
			}
		}		
		
		$this->cache->delete('product');
	}
	
	public function editProduct($product_id, $data) {
        if(!isset($data['model'])){
            $data['model'] = '';
        }
        
        if(!isset($data['product_cross_related'])){
            $data['product_cross_related'] = 0;    
        }
        
		if(!isset($data['delay_delivery'])){
            $data['delay_delivery'] = '0';
        }
	
        $sql_product = "UPDATE " . DB_PREFIX . "product " .
            " SET " .
            "   model = '" . $this->db->escape($data['model']) . "', sku = '" . $this->db->escape($data['sku']) . "', location = '" . $this->db->escape($data['location']) . "', " .
            "   quantity = '" . (int)$data['quantity'] . "', minimum = '" . (int)$data['minimum'] . "', subtract = '" . (int)$data['subtract'] . "', " .
            "   stock_status_id = '" . (int)$data['stock_status_id'] . "', date_available = '" . $this->db->escape($data['date_available']) . "', " .
            "   manufacturer_id = '" . (int)$data['manufacturer_id'] . "', shipping = '" . (int)$data['shipping'] . "', price = '" . (float)$data['price'] . "', " .
            "   cost = '" . (float)$data['cost'] . "', weight = '" . (float)$data['weight'] . "', weight_class_id = '" . (int)$data['weight_class_id'] . "', " .
            "   length = '" . (float)$data['length'] . "', width = '" . (float)$data['width'] . "', height = '" . (float)$data['height'] . "', " .
            "   length_class_id = '" . (int)$data['length_class_id'] . "', status = '" . (int)$data['status'] . "', tax_class_id = '" . (int)$data['tax_class_id'] . "', " .
            "   sort_order = '" . (int)$data['sort_order'] . "', size_guide = '" . $data['size_guide'] . "', date_modified = NOW(), cross_reference = '" . (int)$data['product_cross_related'] . "', product_number = '" . $data['product_number'] . "', " .
            "   low_stock_warning = '" . (int)$data['low_stock_warning'] . "', delivery_time_instock = '" . $this->db->escape($data['delivery_time_instock']) . "', delivery_time_outstock = '" . $this->db->escape($data['delivery_time_outstock']) . "', " . 
			"   youtube_video = '" . $this->db->escape($data['youtube_video']) . "', youtube_video_width = '" . (int)$data['youtube_video_width'] . "', youtube_video_height = '" . (int)$data['youtube_video_height'] . "', delay_delivery = '" . (int)$data['delay_delivery'] . "' " .
            " WHERE product_id = '" . (int)$product_id . "'";
            
		$this->db->query($sql_product);

		if (isset($data['image'])) {
			$this->db->query("UPDATE " . DB_PREFIX . "product SET image = '" . $this->db->escape($data['image']) . "' WHERE product_id = '" . (int)$product_id . "'");
		}
		
        if (isset($data['video'])) {
            $this->db->query("UPDATE " . DB_PREFIX . "product SET video = '" . $this->db->escape($data['video']) . "' WHERE product_id = '" . (int)$product_id . "'");
        }
        
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'");
		
		foreach ($data['product_description'] as $language_id => $value) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "product_description SET product_id = '" . (int)$product_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "', meta_keywords = '" . $this->db->escape($value['meta_keywords']) . "', meta_description = '" . $this->db->escape($value['meta_description']) . "', description = '" . $this->db->escape($value['description']) . "'");
		}

		$this->db->query("DELETE FROM " . DB_PREFIX . "product_to_store WHERE product_id = '" . (int)$product_id . "'");

		if (isset($data['product_store'])) {
			foreach ($data['product_store'] as $store_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_to_store SET product_id = '" . (int)$product_id . "', store_id = '" . (int)$store_id . "'");
			}
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_option WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_option_description WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_option_value WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_option_value_description WHERE product_id = '" . (int)$product_id . "'");
		
		if (isset($data['product_option'])) {
			foreach ($data['product_option'] as $product_option) { 
                if($this->isSaveOption($product_option['product_option_value'])){ 
                    $query = "INSERT INTO " . DB_PREFIX . "product_option SET product_id = '" . (int)$product_id . "', sort_order = '" . (int)$product_option['sort_order'] . "', attribute_id = '" . (int)$product_option['attribute_id'] . "', is_complex = '0'";
                    if(isset($product_option['option_id'])){
                        $query .= ", product_option_id = '" . $product_option['option_id'] . "'";
                    }
				    $this->db->query($query);				
				    $product_option_id = $this->db->getLastId();
				    
				    foreach ($product_option['language'] as $language_id => $language) {
					    $this->db->query("INSERT INTO " . DB_PREFIX . "product_option_description SET product_option_id = '" . (int)$product_option_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = '" . $this->db->escape($language['name']) . "'");
				    }	
				    
				    foreach ($product_option['product_option_value'] as $product_option_value) {
                        if(isset($product_option_value['select_attribute'])){
                            $query_ov = "INSERT INTO " . DB_PREFIX . "product_option_value SET product_option_id = '" . (int)$product_option_id . "', product_id = '" . (int)$product_id . "', quantity = '" . (int)$product_option_value['quantity'] . "', subtract = '" . (int)$product_option_value['subtract'] . "', price = '" . (float)$product_option_value['price'] . "', prefix = '" . $this->db->escape($product_option_value['prefix']) . "', sort_order = '" . (int)$product_option_value['sort_order'] . "', attribute_id = '" . (int)$product_option_value['attribute_id'] . "', attribute_value_id = '" . (int)$product_option_value['attribute_value_id'] . "', product_option_number = '" . $this->db->escape($product_option_value['product_option_number']) . "'";
                            if(isset($product_option_value['option_value_id'])){
                                $query_ov .= ", product_option_value_id = '" . $product_option_value['option_value_id'] . "'";
                            }
						    $this->db->query($query_ov);				
						    $product_option_value_id = $this->db->getLastId();
				    
						    foreach ($product_option_value['language'] as $language_id => $language) {
							    $this->db->query("INSERT INTO " . DB_PREFIX . "product_option_value_description SET product_option_value_id = '" . (int)$product_option_value_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = '" . $this->db->escape($language['name']) . "'");
						    }	
                        }				
				    }
				}
			}
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_discount WHERE product_id = '" . (int)$product_id . "'");

		if (isset($data['product_discount'])) {
			foreach ($data['product_discount'] as $value) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_discount SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$value['customer_group_id'] . "', quantity = '" . (int)$value['quantity'] . "', priority = '" . (int)$value['priority'] . "', price = '" . (float)$value['price'] . "', date_start = '" . $this->db->escape($value['date_start']) . "', date_end = '" . $this->db->escape($value['date_end']) . "'");
			}
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "'");
		
		if (isset($data['product_special'])) {
			foreach ($data['product_special'] as $value) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_special SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$value['customer_group_id'] . "', priority = '" . (int)$value['priority'] . "', price = '" . (float)$value['price'] . "', date_start = '" . $this->db->escape($value['date_start']) . "', date_end = '" . $this->db->escape($value['date_end']) . "', quantity = '" . (int)$value['quantity'] . "'");
			}
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_image WHERE product_id = '" . (int)$product_id . "'");
		
		if (isset($data['product_image'])) {
			foreach ($data['product_image'] as $image) {
                if($image){
        		    $this->db->query("INSERT INTO " . DB_PREFIX . "product_image SET product_id = '" . (int)$product_id . "', image = '" . $this->db->escape($image) . "'");
                }
			}
		}
		
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_color WHERE product_id = '" . (int)$product_id . "'");		
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_color_image WHERE product_id = '" . (int)$product_id . "'");
		if (isset($data['product_color'])) {
            $query_option = "INSERT INTO " . DB_PREFIX . "product_option SET product_id = '" . (int)$product_id . "', attribute_id = '" . (int)$data['color_attribute_id'] . "', sort_order = '10', is_complex = '1'";
			if(isset($data['product_color'][0]['option_id'])){
                $query_option .= ", product_option_id = '" . $data['product_color'][0]['option_id'] . "'";
            }              
            $this->db->query($query_option);				
			$option_id = $this->db->getLastId();	
            foreach ($data['product_color_language'] as $language_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_option_description SET product_option_id = '" . (int)$option_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = 'Farve'");
			}
				
            usort($data['product_color'], 'usort_compare_color');		
			foreach ($data['product_color'] as $color) {  
                $query_ov = "INSERT INTO " . DB_PREFIX . "product_option_value SET product_option_id = '" . (int)$option_id . "', product_id = '" . (int)$product_id . "', quantity = '1000', subtract = '1', price = '0', prefix = '+', sort_order = '0'";      		
        		if(isset($color['color_ov_id'])){
                    $query_ov .= ", product_option_value_id = '" . $color['color_ov_id'] . "'";
                }
                $this->db->query($query_ov);        									
        		$option_value_id = $this->db->getLastId();
				foreach ($data['product_color_language'] as $language_id) {
					$this->db->query("INSERT INTO " . DB_PREFIX . "product_option_value_description SET product_option_value_id = '" . (int)$option_value_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = '" . $this->db->escape($color['name']) . "'");
				}
				
				if(isset($color['image_list'])){
					reset($color['image_list']);
					$color['image'] = current($color['image_list']);
				}
				
                $query = "INSERT INTO " . DB_PREFIX . "product_color SET product_id = '" . (int)$product_id . "', image = '" . $this->db->escape($color['image']) . "', color_name='" . $this->db->escape($color['name']) . "', color_image='" . $this->db->escape($color['color_image']) . "', option_id = '" . (int)$option_id . "', option_value_id = '" . (int)$option_value_id . "', sort_order = '" . $this->db->escape($color['sort_order']) . "', attribute_id = '" . (int)$data['color_attribute_id'] . "', attribute_value_id = '" . (int)$color['color_av_id'] . "'";    
                if(isset($color['color_id'])){
                    $query .= ", product_color_id = '" . $color['color_id'] . "'";
                }                
                
				$this->db->query($query);
				if(isset($color['image_list'])){
					$color_id = $this->db->getLastId();
					foreach ($color['image_list'] as $image) {
						$this->db->query("INSERT INTO " . DB_PREFIX . "product_color_image SET product_id = '" . (int)$product_id . "', color_id = '" . (int)$color_id . "', image = '" . $this->db->escape($image) . "'");
					} 
				}       		
			}
		}			
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_to_download WHERE product_id = '" . (int)$product_id . "'");
		
		if (isset($data['product_download'])) {
			foreach ($data['product_download'] as $download_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_to_download SET product_id = '" . (int)$product_id . "', download_id = '" . (int)$download_id . "'");
			}
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int)$product_id . "'");
		
		if (isset($data['product_category'])) {
			foreach ($data['product_category'] as $category_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_to_category SET product_id = '" . (int)$product_id . "', category_id = '" . (int)$category_id . "'");
			}		
		}

		$this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$product_id . "'");

		if (isset($data['product_related'])) {
            if($data['product_cross_related']) {
			    foreach ($data['product_related'] as $related_id) {
				    $this->db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$product_id . "', related_id = '" . (int)$related_id . "'");
				    $this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$related_id . "' AND related_id = '" . (int)$product_id . "'");
				    $this->db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$related_id . "', related_id = '" . (int)$product_id . "'");
			    }
            }
            else{
                foreach ($data['product_related'] as $related_id) {
                    $this->db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$product_id . "', related_id = '" . (int)$related_id . "'");
                    $this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$related_id . "' AND related_id = '" . (int)$product_id . "'");                   
                }  
            }
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "url_alias WHERE query = 'product_id=" . (int)$product_id. "'");
		
		if ($data['keyword']) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'product_id=" . (int)$product_id . "', keyword = '" . $this->db->escape($data['keyword']) . "'");
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_tags WHERE product_id = '" . (int)$product_id. "'");
		
		foreach ($data['product_tags'] as $language_id => $value) {
			$tags = explode(',', $value);
			foreach ($tags as $tag) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "product_tags SET product_id = '" . (int)$product_id . "', language_id = '" . (int)$language_id . "', tag = '" . $this->db->escape(trim($tag)) . "'");
			}
		}
		
		$this->cache->delete('product');
	}
	
	public function copyProduct($product_id) {
        $sql = "SELECT DISTINCT * " . 
            " FROM " . DB_PREFIX . "product p " . 
            " LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) " .
            " WHERE p.product_id = '" . (int)$product_id . "' AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
		$query = $this->db->query($sql);
		
		if ($query->num_rows) {
			$data = array();
			
			$data = $query->row;
			
			$data = array_merge($data, array('product_description' => $this->getProductDescriptions($product_id)));
			$data = array_merge($data, array('product_option' => $this->getProductOptions($product_id)));
						
			$data['keyword'] = '';
						
			$data['product_image'] = array();
			
			$results = $this->getProductImages($product_id);
			
			foreach ($results as $result) {
				$data['product_image'][] = $result['image'];
			}
			
			$data = array_merge($data, array('product_discount' => $this->getProductDiscounts($product_id)));
			$data = array_merge($data, array('product_special' => $this->getProductSpecials($product_id)));
			$data = array_merge($data, array('product_download' => $this->getProductDownloads($product_id)));
			$data = array_merge($data, array('product_category' => $this->getProductCategories($product_id)));
			$data = array_merge($data, array('product_store' => $this->getProductStores($product_id)));
			$data = array_merge($data, array('product_related' => $this->getProductRelated($product_id)));
			$data = array_merge($data, array('product_tags' => $this->getProductTags($product_id)));
			
			$this->addProduct($data);
		}
	}
	
	public function deleteProduct($product_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_option WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_option_description WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_option_value WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_option_value_description WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_discount WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_image WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_to_download WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "review WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_to_store WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "url_alias WHERE query = 'product_id=" . (int)$product_id. "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_tags WHERE product_id='" . (int)$product_id. "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_color WHERE product_id = '" . (int)$product_id . "'");
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_color_image WHERE product_id = '" . (int)$product_id . "'");
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_category_sort WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_manufacturer_sort WHERE product_id = '" . (int)$product_id . "'");
		
		$this->cache->delete('product');
	}
	
	public function getProduct($product_id) {
		$query = $this->db->query("SELECT DISTINCT *, (SELECT keyword FROM " . DB_PREFIX . "url_alias WHERE query = 'product_id=" . (int)$product_id . "') AS keyword FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) WHERE p.product_id = '" . (int)$product_id . "' AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
				
		return $query->row;
	}
	
	public function getProducts($data = array()) {
		$cache = md5(http_build_query($data));		
		$product_data = $this->cache->get('product.' . (int)$this->config->get('config_language_id') . '.' . $cache);
		if ($product_data) {
			return $product_data;
		}
		
		if ($data) {
			$sql = "SELECT p.*,pd.name, cd.name AS category, m.name AS manufacturer " . //, pcs.product_sort_order " . //, pms.product_msort_order " .
                " FROM " . DB_PREFIX . "product p" .
                " LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id)" .
                " LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (p.product_id = p2c.product_id)" .
                " LEFT JOIN " . DB_PREFIX . "category_description cd ON (p2c.category_id = cd.category_id)" .
                //" LEFT JOIN " . DB_PREFIX . "product_category_sort pcs ON (p.product_id = pcs.product_id AND p2c.category_id = pcs.category_id)" .
                " LEFT JOIN " . DB_PREFIX . "manufacturer m ON (m.manufacturer_id = p.manufacturer_id)" .
                //" LEFT JOIN " . DB_PREFIX . "product_manufacturer_sort pms ON (p.product_id = pms.product_id AND m.manufacturer_id = pms.manufacturer_id)" .                
                " WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
		
			if (isset($data['filter_name']) && !is_null($data['filter_name'])) {
				$sql .= " AND LCASE(pd.name) LIKE '%" . strtolower($this->db->escape(strtolower($data['filter_name']))) . "%'";
			}

			if (isset($data['filter_model']) && !is_null($data['filter_model'])) {
				$sql .= " AND LCASE(p.model) LIKE '%" . $this->db->escape(strtolower($data['filter_model'])) . "%'";
			}
                        
            if (isset($data['filter_category']) && !is_null($data['filter_category'])) {
				$sql .= " AND p2c.category_id = '" . $this->db->escape($data['filter_category']) . "'";
			}
			
            if (isset($data['filter_sku']) && !is_null($data['filter_sku'])) {
                $sql .= " AND p.sku LIKE '%" . $this->db->escape($data['filter_sku']) . "%'";
            }
            
            if (isset($data['filter_manufacturer']) && !is_null($data['filter_manufacturer'])) {
                $sql .= " AND p.manufacturer_id = '" . $this->db->escape($data['filter_manufacturer']) . "'";
            }
            
			if (isset($data['filter_quantity']) && !is_null($data['filter_quantity'])) {
				$sql .= " AND p.quantity = '" . $this->db->escape($data['filter_quantity']) . "'";
			}
			
			if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
				$sql .= " AND p.status = '" . (int)$data['filter_status'] . "'";
			}

            if (isset($data['filter_price']) && !is_null($data['filter_price'])) {
                $sql .= " AND p.price = '" . (int)$data['filter_price'] . "'";
            }
            
			$sort_data = array(
				'pd.name',
				'p.model',
                'category',
                'p.sku',
                'manufacturer',
				'p.quantity',
				'p.status',
				'p.sort_order',
                'p.price',   
                //'pcs.product_sort_order',
                //'pms.product_msort_order',
			);	
			$sql .= " GROUP BY pd.product_id"  ;

			if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
				$sql .= " ORDER BY " . $data['sort'];	
			} else {
				$sql .= " ORDER BY pd.name";	
			}
			
			if (isset($data['order']) && ($data['order'] == 'DESC')) {
				$sql .= " DESC";
			} else {
				$sql .= " ASC";
			}
		
			if (isset($data['start']) || isset($data['limit'])) {
				if ($data['start'] < 0) {
					$data['start'] = 0;
				}				

				if ($data['limit'] < 1) {
					$data['limit'] = 20;
				}	
			
				$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
			}	
			        
			$query = $this->db->query($sql);
		
			$this->cache->set('product.' . (int)$this->config->get('config_language_id') . '.' . $cache, $query->rows);
			
			return $query->rows;
		} else {
			$product_data = $this->cache->get('product.' . $this->config->get('config_language_id'));
		
			if (!$product_data) {
				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY pd.name ASC");
	
				$product_data = $query->rows;
			
				$this->cache->set('product.' . $this->config->get('config_language_id'), $product_data);
			}	
	
			return $product_data;
		}
	}    
		
	public function addFeatured($data) {
      	$this->db->query("DELETE FROM " . DB_PREFIX . "product_featured");
      	
		if (isset($data['featured_product'])) {
      		foreach ($data['featured_product'] as $product_id) {
        		$this->db->query("INSERT INTO " . DB_PREFIX . "product_featured SET product_id = '" . (int)$product_id . "'");
      		}			
		}
	}
	
	public function getFeaturedProducts() {
		$query = $this->db->query("SELECT product_id FROM " . DB_PREFIX . "product_featured");
		
		$featured = array();
		
		foreach ($query->rows as $product) {
			$featured[] = $product['product_id'];
		}
		return $featured;
	}
	
    public function addSpecialFeatured($data) {  
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_special_featured WHERE feature = 'product_home'");
          
        if (isset($data['product_featured'])) {
            foreach ($data['product_featured'] as $featured) {
                $sql = "INSERT INTO " . DB_PREFIX . "product_special_featured SET " . 
                    " product_id = '" . (int)$featured['product_id'] . "', " .
                    " name = '" . $this->db->escape($featured['name']) . "', " .
                    " price = '" . $this->db->escape($featured['price']) . "', " .
                    " image = '" . $this->db->escape($featured['image']) . "', " .
                    " feature = 'product_home'";
                       
                $this->db->query($sql);
            }            
        }
    }
    
    public function getSpecialFeaturedProducts() {
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_special_featured WHERE feature = 'product_home'");
        
        $featured = array();         
        foreach ($query->rows as $product) {
            $featured[] = array(
                'product_id'    => $product['product_id'],
                'name'          => $product['name'],
                'price'         => $product['price'],
                'image'         => $product['image'],
            );
        }
        return $featured;
    }

    public function getSpecialLeftProducts() {
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_special_featured WHERE feature = 'product_left'");

        $featured = array();
        foreach ($query->rows as $product) {
            $featured[] = array(
                'product_id'    => $product['product_id'],
                'name'          => $product['name'],
                'price'         => $product['price'],
                'image'         => $product['image'],
            );
        }
        return $featured;
    }

    public function addSpecialLeftProduct($data) {
        $this->db->query("DELETE FROM " . DB_PREFIX . "product_special_featured WHERE feature = 'product_left'");

        if (isset($data['product_left'])) {
            foreach ($data['product_left'] as $featured) {
                $sql = "INSERT INTO " . DB_PREFIX . "product_special_featured SET " .
                    " product_id = '" . (int)$featured['product_id'] . "', " .
                    " name = '" . $this->db->escape($featured['name']) . "', " .
                    " price = '" . $this->db->escape($featured['price']) . "', " .
                    " image = '" . $this->db->escape($featured['image']) . "', " .
                    " feature = 'product_left'";

                $this->db->query($sql);
            }
        }
    }

	public function getProductsByKeyword($keyword) {
		if ($keyword) {
			$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND (LCASE(pd.name) LIKE '%" . $this->db->escape(strtolower($keyword)) . "%' OR LCASE(p.model) LIKE '%" . $this->db->escape(strtolower($keyword)) . "%')");
									  
			return $query->rows;
		} else {
			return array();	
		}		
	} 
	
	public function getProductsByCategoryId($category_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (p.product_id = p2c.product_id) WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND p2c.category_id = '" . (int)$category_id . "' ORDER BY pd.name ASC");
								  
		return $query->rows;
	} 
	
	public function getProductDescriptions($product_id) {
		$product_description_data = array();
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'");
		
		foreach ($query->rows as $result) {
			$product_description_data[$result['language_id']] = array(
				'name'             => $result['name'],
				'meta_keywords'    => $result['meta_keywords'],
				'meta_description' => $result['meta_description'],
				'description'      => $result['description']
			);
		}
		
		return $product_description_data;
	}

	public function getProductOptions($product_id) {
		$product_option_data = array();
		
        //$sql = "SELECT * FROM " . DB_PREFIX . "product_option WHERE p.product_id = '" . (int)$product_id . "' AND (ISNULL(is_complex) OR is_complex = 0) ORDER BY sort_order";
        $sql = "SELECT p.*, a.description FROM " . DB_PREFIX . "product_option p LEFT JOIN " . DB_PREFIX . "attribute a ON p.attribute_id = a.attribute_id WHERE p.product_id = '" . (int)$product_id . "' AND IFNULL(p.is_complex, 0) = 0 ORDER BY p.sort_order";
		$product_option = $this->db->query($sql);
		
		foreach ($product_option->rows as $product_option) { 
			$product_option_value_data = array();
			
			$product_option_value = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value WHERE product_option_id = '" . (int)$product_option['product_option_id'] . "' ORDER BY sort_order");
			
			foreach ($product_option_value->rows as $product_option_value) {
				$product_option_value_description_data = array();
				
				$product_option_value_description = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value_description WHERE product_option_value_id = '" . (int)$product_option_value['product_option_value_id'] . "'");

				foreach ($product_option_value_description->rows as $result) {
					$product_option_value_description_data[$result['language_id']] = array('name' => $result['name']);
				}
			
				$product_option_value_data[] = array(
					'product_option_value_id' => $product_option_value['product_option_value_id'],
					'language'                => $product_option_value_description_data,
         			'quantity'                => $product_option_value['quantity'],
					'subtract'                => $product_option_value['subtract'],
					'price'                   => $product_option_value['price'],
         			'prefix'                  => $product_option_value['prefix'],
					'sort_order'              => $product_option_value['sort_order'],
                    'attribute_id'            => $product_option_value['attribute_id'],
                    'attribute_value_id'      => $product_option_value['attribute_value_id'],
                    'product_option_number'   => $product_option_value['product_option_number'],					
				);
			}
			
			$product_option_description_data = array();
			
			$product_option_description = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_description WHERE product_option_id = '" . (int)$product_option['product_option_id'] . "'");

			foreach ($product_option_description->rows as $result) {
				$product_option_description_data[$result['language_id']] = array('name' => $result['name']);
			}
		
        	$product_option_data[] = array(
        		'product_option_id'    => $product_option['product_option_id'],
				'language'             => $product_option_description_data,
				'product_option_value' => $product_option_value_data,
				'sort_order'           => $product_option['sort_order'],
                'attribute_id'         => $product_option['attribute_id'],
                'description'          => $product_option['description'],
        	);
      	}	
		
		return $product_option_data;
	}
	
	public function getProductImages($product_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_image WHERE product_id = '" . (int)$product_id . "'");
		
		return $query->rows;
	}
	
    public function getProductColors($product_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_color WHERE product_id = '" . (int)$product_id . "'  ORDER BY sort_order, product_color_id");
		
		return $query->rows;
	}
    
	public function getProductColorImages($product_id, $color_id) {		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_color_image WHERE product_id = '" . (int)$product_id . "' AND color_id = '" . (int)$color_id . "' ORDER BY color_image_id");
		
		return $query->rows;
	}
	
	public function getProductDiscounts($product_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_discount WHERE product_id = '" . (int)$product_id . "' ORDER BY quantity, priority, price");
		
		return $query->rows;
	}
	
	public function getProductSpecials($product_id) {
		//$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' ORDER BY priority, price");
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' ORDER BY product_special_id, priority, price ASC");
		
		return $query->rows;
	}
	
	public function getProductDownloads($product_id) {
		$product_download_data = array();
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_download WHERE product_id = '" . (int)$product_id . "'");
		
		foreach ($query->rows as $result) {
			$product_download_data[] = $result['download_id'];
		}
		
		return $product_download_data;
	}

	public function getProductStores($product_id) {
		$product_store_data = array();
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_store WHERE product_id = '" . (int)$product_id . "'");

		foreach ($query->rows as $result) {
			$product_store_data[] = $result['store_id'];
		}
		
		return $product_store_data;
	}
	
	public function getProductCategories($product_id) {
		$product_category_data = array();
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int)$product_id . "'");
		
		foreach ($query->rows as $result) {
			$product_category_data[] = $result['category_id'];
		}

		return $product_category_data;
	}

	public function getProductRelated($product_id) {
		$product_related_data = array();
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$product_id . "'");
		
		foreach ($query->rows as $result) {
			$product_related_data[] = $result['related_id'];
		}
		
		return $product_related_data;
	}
	
	public function getProductTags($product_id) {
		$product_tag_data = array();
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_tags WHERE product_id = '" . (int)$product_id . "'");
		
		$tag_data = array();
		
		foreach ($query->rows as $result) {
			$tag_data[$result['language_id']][] = $result['tag'];
		}
		
		foreach ($tag_data as $language => $tags) {
			$product_tag_data[$language] = implode(',', $tags);
		}
		
		return $product_tag_data;
	}
	
	public function getTotalProducts($data = array()) {
		//$sql = "SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (p.product_id = p2c.product_id) LEFT JOIN " . DB_PREFIX . "category_description cd ON (p2c.category_id = cd.category_id) WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
        $sql = "SELECT COUNT(DISTINCT(p.product_id)) AS total FROM " . DB_PREFIX . "product p" .
            " LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id)" .
            " LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (p.product_id = p2c.product_id)" .
            " LEFT JOIN " . DB_PREFIX . "category_description cd ON (p2c.category_id = cd.category_id)" .
            " LEFT JOIN " . DB_PREFIX . "manufacturer m ON (m.manufacturer_id = p.manufacturer_id)" .
            " WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
		
		if (isset($data['filter_name']) && !is_null($data['filter_name'])) {
			$sql .= " AND LCASE(pd.name) LIKE '%" . $this->db->escape(strtolower($data['filter_name'])) . "%'";
		}

        if (isset($data['filter_category']) && !is_null($data['filter_category'])) {
            $sql .= " AND p2c.category_id = '" . $this->db->escape($data['filter_category']) . "'";
        }
            
		if (isset($data['filter_model']) && !is_null($data['filter_model'])) {
			$sql .= " AND LCASE(p.model) LIKE '%" . $this->db->escape(strtolower($data['filter_model'])) . "%'";
		}
		        
        if (isset($data['filter_sku']) && !is_null($data['filter_sku'])) {
            $sql .= " AND p.sku LIKE '%" . $this->db->escape($data['filter_sku']) . "%'";
        }
        
        if (isset($data['filter_manufacturer']) && !is_null($data['filter_manufacturer'])) {
            $sql .= " AND p.manufacturer_id = '" . $this->db->escape($data['filter_manufacturer']) . "'";
        }
        
		if (isset($data['filter_quantity']) && !is_null($data['filter_quantity'])) {
			$sql .= " AND p.quantity = '" . $this->db->escape($data['filter_quantity']) . "'";
		}
		
		if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
			$sql .= " AND p.status = '" . (int)$data['filter_status'] . "'";
		}
        
		$query = $this->db->query($sql);
		
		return $query->row['total'];
	}	
	
	public function getTotalProductsByStockStatusId($stock_status_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE stock_status_id = '" . (int)$stock_status_id . "'");

		return $query->row['total'];
	}
	
	public function getTotalProductsByImageId($image_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE image_id = '" . (int)$image_id . "'");

		return $query->row['total'];
	}
	
	public function getTotalProductsByTaxClassId($tax_class_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE tax_class_id = '" . (int)$tax_class_id . "'");

		return $query->row['total'];
	}
	
	public function getTotalProductsByWeightClassId($weight_class_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE weight_class_id = '" . (int)$weight_class_id . "'");

		return $query->row['total'];
	}
	
	public function getTotalProductsByLengthClassId($length_class_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE length_class_id = '" . (int)$length_class_id . "'");

		return $query->row['total'];
	}
	
	public function getTotalProductsByOptionId($option_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product_to_option WHERE option_id = '" . (int)$option_id . "'");

		return $query->row['total'];
	}

	public function getTotalProductsByDownloadId($download_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product_to_download WHERE download_id = '" . (int)$download_id . "'");
		
		return $query->row['total'];
	}
	
	public function getTotalProductsByManufacturerId($manufacturer_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "product WHERE manufacturer_id = '" . (int)$manufacturer_id . "'");

		return $query->row['total'];
	}
    
    public function getProductColorAttribute($product_id) {
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option WHERE product_id = '" . (int)$product_id . "'  ORDER BY sort_order, product_color_id");
        
        return $query->rows;
    }
    
    private function isSaveOption($options){
        $result = false;
        foreach($options as $item){    
            if(isset($item['select_attribute'])){
                $result = true;
            }
        }
        
        return $result;
    }
	
	public function getProductsAutocomplete($data = array()) {
		if ($data) {
			$sql = "SELECT p.*,pd.name, cd.name AS category, m.name AS manufacturer " .
                " FROM " . DB_PREFIX . "product p" .
                " LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id)" .
                " LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (p.product_id = p2c.product_id)" .
                " LEFT JOIN " . DB_PREFIX . "category_description cd ON (p2c.category_id = cd.category_id)" .                
                " LEFT JOIN " . DB_PREFIX . "manufacturer m ON (m.manufacturer_id = p.manufacturer_id)" .                
                " WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
						
			if (isset($data['filter_name_sku']) && !is_null($data['filter_name_sku'])) {
				$name_or_sku = strtolower($this->db->escape(strtolower($data['filter_name_sku'])));
				$sql .= " AND (LCASE(pd.name) LIKE '%" . $name_or_sku . "%' OR LCASE(p.sku) LIKE '%" . $name_or_sku . "%')";
			}
                        
            if (isset($data['filter_category']) && !is_null($data['filter_category'])) {
				$sql .= " AND p2c.category_id = '" . $this->db->escape($data['filter_category']) . "'";
			}
			
            if (isset($data['filter_manufacturer']) && !is_null($data['filter_manufacturer'])) {
                $sql .= " AND p.manufacturer_id = '" . $this->db->escape($data['filter_manufacturer']) . "'";
            }
            
			if (isset($data['filter_quantity']) && !is_null($data['filter_quantity'])) {
				$sql .= " AND p.quantity = '" . $this->db->escape($data['filter_quantity']) . "'";
			}
			
			if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
				$sql .= " AND p.status = '" . (int)$data['filter_status'] . "'";
			}

            if (isset($data['filter_price']) && !is_null($data['filter_price'])) {
                $sql .= " AND p.price = '" . (int)$data['filter_price'] . "'";
            }
           
			$sql .= " GROUP BY pd.product_id ORDER BY pd.name ASC";
		
			if (isset($data['start']) || isset($data['limit'])) {
				if ($data['start'] < 0) {
					$data['start'] = 0;
				}				

				if ($data['limit'] < 1) {
					$data['limit'] = 20;
				}	
			
				$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
			}	
			        
			$query = $this->db->query($sql);
		
			return $query->rows;
		}
		else {
			$product_data = $this->cache->get('product.' . $this->config->get('config_language_id'));
		
			if (!$product_data) {
				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY pd.name ASC");
	
				$product_data = $query->rows;
			
				$this->cache->set('product.' . $this->config->get('config_language_id'), $product_data);
			}	
	
			return $product_data;
		}
	}
	
	public function getActiveProductOptions($product_id) {
		$product_option_data = array();
		
		$product_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option WHERE product_id = '" . (int)$product_id . "' ORDER BY sort_order");
		
		foreach ($product_option_query->rows as $product_option) {
			$product_option_value_data = array();
			
			$product_option_value_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value WHERE product_option_id = '" . (int)$product_option['product_option_id'] . "' ORDER BY sort_order");
			
			foreach ($product_option_value_query->rows as $product_option_value) {
				$product_option_value_description_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value_description WHERE product_option_value_id = '" . (int)$product_option_value['product_option_value_id'] . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");
			
				if(!empty($product_option_value_description_query->row)){
					if($product_option_value['quantity'] > 0){
						$product_option_value_data[] = array(
							'product_option_value_id' => $product_option_value['product_option_value_id'],
							'name'                    => $product_option_value_description_query->row['name'],
							'price'                   => $product_option_value['price'],
							'prefix'                  => $product_option_value['prefix'],
							'product_option_number'   => $product_option_value['product_option_number'],
							'quantity'                => $product_option_value['quantity'],
						);
					}
				}
			}
						
			$product_option_description_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_description WHERE product_option_id = '" . (int)$product_option['product_option_id'] . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");
						
        	$product_option_data[] = array(
        		'product_option_id' => $product_option['product_option_id'],
				'name'              => $product_option_description_query->row['name'],
				'option_value'      => $product_option_value_data,
				'sort_order'        => $product_option['sort_order']
        	);
      	}	
		
		return $product_option_data;
	}
}

function usort_compare_color($a, $b){
    if(!isset($a['color_id']) || !isset($b['color_id'])){
        return 1;    
    }
    
    // $a == $b    
    if($a['color_id'] == $b['color_id']){
        return 0;    
    }
    
    // $a < $b      
    if(($a['color_id'] < $b['color_id'])){
        return -1;  
    }   
    else{
        return 1;
    }
}
?>